<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="3" :xs="24">
        <div class="head-container">
          <el-input
            v-model="roleName"
            placeholder="请输入角色名"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container" style="min-height: 520px;">
          <div v-for="r in roleOptions" :class="{'selectUrl': r==currRole}" class="selectDiv"
               @click="handleNodeClick(r)" v-show="!roleName || r.roleName.indexOf(roleName)>=0">
            {{r.roleName}}
          </div>
        </div>
      </el-col>
      <el-col :span="3" :xs="24">
        <div class="head-container">
          <el-input
            v-model="userTableName"
            placeholder="请输入表名"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container" style="min-height: 520px;">
          <div v-for="t in userTables" :class="{'selectUrl': t==currFormDef}" class="selectDiv"
               @click="handleNodeClickForUserTable(t)" v-show="!userTableName || t.formDefName.indexOf(userTableName)>=0">
            {{t.formDefName}}
          </div>
        </div>
      </el-col>
      <el-col :span="18" :xs="24">
        <div v-if="!currRole.roleKey || !currFormDef.formDefName" style="padding: 80px; text-align: center; color: #bababa; font-size: 24px;">请选择数据表进行查询</div>
        <div v-else>
          <el-tabs type="card" v-model="first">
            <el-tab-pane label="表权限配置" name="first" class="tablePermissions">
              <el-form ref="form" label-width="80px">
                <el-form-item label="角色">
                  <el-input :value="currRole.roleName" readonly="readonly" />
                </el-form-item>
                <el-form-item label="表">
                  <el-input :value="currFormDef.formDefName" readonly="readonly" />
                </el-form-item>
                <el-form-item label="表权限">
                  <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
                  <el-checkbox-group v-model="tablePermissionOptionsSelected" @change="handleCheckedCitiesChange" style="margin-top: 5px;">
                    <el-checkbox v-for="per in tablePermissionOptions" :label="per.permission" :key="per.permission">{{per.desc+"["+per.permission+"]"}}</el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
                <el-form-item>
                  <el-alert style="margin-bottom: 10px;"
                    title="为保证编辑，审核，删除等权限正常使用，请同时分配查看权限"
                    type="warning" show-icon
                    close-text="知道了">
                  </el-alert>
                  <el-button type="primary" @click="saveTablePermission">保存</el-button>
                  <el-button>重置</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="字段权限" name="second" class="columnPermissions">
              <el-table :data="columns" height="500" border style="width: 100%">
                <el-table-column prop="columnName" label="字段名" width="180"></el-table-column>
                <el-table-column prop="columnTitle" label="标题" width="200"></el-table-column>
                <el-table-column prop="permissions" label="权限">
                  <template slot-scope="scope">
                    <el-checkbox-group v-model="scope.row.permissions">
                      <el-checkbox v-for="per in columnPermissionOptions" :label="per.permission" :key="per.permission">{{per.desc+"["+per.permission+"]"}}</el-checkbox>
                    </el-checkbox-group>
                  </template>
                </el-table-column>
              </el-table>
              <div style="padding-left: 20px; padding-top: 20px;">
                <el-button type="primary" @click="saveColumnPermission">保存</el-button>
                <el-button>重置</el-button>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
    import {listRole} from "@/api/system/role";
    import {getUserTableSettings} from "@/api/renshi/person/userTableSetting";
    import {
        getUserColumnPermission,
        getUserTablePermission,
        saveUserColumnPermission,
        saveUserTablePermission
    } from "@/api/renshi/person/userTablePermission";
    import Treeselect from "@riophae/vue-treeselect";
    import "@riophae/vue-treeselect/dist/vue-treeselect.css";
    import {Loading} from 'element-ui';

    export default {
        name: "userTablePermissionEdit.vue",
        components: { Treeselect },
        data() {
            return {
                roleOptions: [],
                roleName: null,
                userTables: [],
                userTableName: null,
                currRole: {},
                currFormDef: {},
                checkedCities: [],
                isIndeterminate: true,
                checkAll: false,
                columns: [],
                tablePermissionOptionsSelected: [],
                tablePermissionOptions: [
                    {permission: "VIEW", desc: "查看"},
                    {permission: "EDIT", desc: "编辑"},
                    {permission: "INSERT", desc: "新增"},
                    {permission: "REMOVE", desc: "删除"},
                    {permission: "AUDIT", desc: "审核"},
                ],
                columnPermissionOptions: [
                    {permission: "VIEW", desc: "查看"},
                    {permission: "EDIT", desc: "编辑"},
                    {permission: "AUDIT", desc: "审核"},
                ],
                first: 'first'
            };
        },
        watch: {
            // 根据名称筛选部门树
            roleName(val) {
                //this.$refs.tree.filter(val);
            },
            userTableName(val) {
                //this.$refs.treeForUserTable.filter(val);
            }
        },
        created() {
            this.getTreeselect();
        },
        methods: {
            /** 查询角色下拉树结构 */
            getTreeselect() {
                listRole({pageNum:1,pageSize:99999}).then(response => {
                    this.roleOptions = response.rows;
                });
                getUserTableSettings({pageNum:1,pageSize:99999}).then(response => {
                    this.userTables = response.rows;
                });
            },
            // 筛选节点
            filterNode(value, data) {
                if (!value) return true;
                return data.roleName.indexOf(value) !== -1;
            },
            // 节点单击事件
            handleNodeClick(data) {
                this.currRole = data;
                this.currFormDef = {};
            },
            // 筛选节点
            filterNodeForUserTable(value, data) {
                if (!value) return true;
                return data.formDefName.indexOf(value) !== -1;
            },
            // 节点单击事件
            handleNodeClickForUserTable(data) {
                this.currFormDef = data;
                if(this.currRole) {//加载数据
                    this.loadPermissions();
                    this.loadPermissionsForColumn();
                }
            },
            loadPermissions() {
                if(!this.currRole.roleKey || !this.currFormDef.formDefKey) {
                    return;
                }
                let loadingInstance = Loading.service({
                    target: '.tablePermissions'
                });
                getUserTablePermission(this.currRole.roleKey, this.currFormDef.formDefKey).then(res => {
                    if(res.data && res.data.length>0) {
                        this.tablePermissionOptionsSelected = res.data.map(e => e.permission);
                    }
                    this.$nextTick(() => {
                        loadingInstance.close();
                    });
                });
            },
            loadPermissionsForColumn() {
                if(!this.currRole.roleKey || !this.currFormDef.formDefKey) {
                    return;
                }
                let loadingInstance = Loading.service({
                    target: '.columnPermissions'
                });
                getUserColumnPermission(this.currRole.roleKey, this.currFormDef.formDefKey).then(res => {
                    this.columns = res.data || [];
                    this.$nextTick(() => {
                        loadingInstance.close();
                    });
                });
            },
            saveTablePermission() {
                let data = [];
                if(this.tablePermissionOptionsSelected && this.tablePermissionOptionsSelected.length>0) {
                    data = this.tablePermissionOptionsSelected.map(e => {
                        return {"permission": e};
                    })
                }
                let roleKey = this.currRole.roleKey;
                let formDefKey = this.currFormDef.formDefKey;
                this.$confirm('是否保存表权限?', "警告", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(function () {
                    return saveUserTablePermission(roleKey, formDefKey, data);
                }).then(() => {
                    this.loadPermissions();
                    this.msgSuccess("保存成功");
                })
            },
            saveColumnPermission() {
                let data = [];
                if(this.columns && this.columns.length>0) {
                    this.columns.forEach(col => {
                        col.permissions.forEach(e => {
                            data.push({"permission": e, "columnName": col.columnName, "columnTitle": col.columnTitle});
                        });
                    });
                }
                let roleKey = this.currRole.roleKey;
                let formDefKey = this.currFormDef.formDefKey;
                this.$confirm('是否保存字段权限?', "警告", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(function () {
                    return saveUserColumnPermission(roleKey, formDefKey, data);
                }).then(() => {
                    this.loadPermissions();
                    this.msgSuccess("保存成功");
                })
            },
            handleCheckAllChange(val) {
                this.tablePermissionOptionsSelected = val ? this.tablePermissionOptions.map(e=>e.permission) : [];
                this.isIndeterminate = false;
            },
            handleCheckedCitiesChange(value) {
                let checkedCount = value.length;
                this.checkAll = checkedCount === this.tablePermissionOptions.length;
                this.isIndeterminate = checkedCount > 0 && checkedCount < this.tablePermissionOptions.length;
            }
        }
    };
</script>
<style>
  .selectUrl {
    background: #f7f7f7;
    color: #409EFF;
  }
  .selectDiv {
    border-right: 1px solid #ccc;
    font-size: 16px;
    cursor: pointer;
    padding: 5px;
  }
</style>
